<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sample_model extends CI_Model {
    public function getAllSamples($bizId) {
        $samples = array();
        $this->db->where('busiId', $bizId);
        $this->db->order_by('addTime', 'DESC');
        $query = $this->db->get('sample');
        foreach ($query->result() as $row) {
            $samples[] = array(
                'id'      => $row->id,
                'busiId'  => $row->busiId,
                'cover'   => $row->cover,
                'title'   => $row->title,
                'intro'   => $row->intro,
                'type'    => $row->type,
                'typeId'  => $row->typeId,
                'addTime' => $row->addTime,
            );
        }

        return $samples;
    }

    public function getSampleById($id) {
        $id    = intval($id);
        $sql   = "SELECT * FROM `sample` WHERE id={$id};";
        $query = $this->db->query($sql);
        $sample = $query->row_array();
        if (!$sample || !isset($sample)) {
            $sample = array();
        }

        return $sample;
    }

    public function getSamplePics($sampleId) {
        $pics = array();
        $sampleId = intval($sampleId);
        $this->db->where('sampleId', $sampleId);
        $this->db->order_by('id', 'DESC');
        $query = $this->db->get('samplePics');
        foreach ($query->result() as $row) {
            $pics[] = array(
                'id'       => $row->id,
                'busiId'   => $row->busiId,
                'sampleId' => $row->sampleId,
                'url'      => $row->url,
            );
        }

        return $pics;
    }

    public function addSample($bizId, $title, $intro, $typeId, $typeName, $addTime, $cover, $pics) {
        $data = array(
            'busiId' => $bizId,
            'cover'  => $cover,
            'title'  => $title,
            'intro'  => $intro,
            'type'   => $typeName,
            'typeId' => $typeId,
            'addTime' => $addTime
        );

        $this->db->insert('sample', $data);

        $sampleId = $this->db->insert_id();

        foreach ($pics as $pic) {
            $data = array(
                'busiId'   => $bizId,
                'sampleId' => $sampleId,
                'url'      => $pic,
            );

            $this->db->insert('samplePics', $data);
        }

        return true;
    }

    public function delSample($id) {
        $this->db->delete('sample', array('id' => $id));
        $this->db->delete('samplePics', array('sampleId' => $id))
        return true;
    }

    public function setTop($sampleId)($id) {
        $id = intval($id);
        $this->db->where('id', $id);
        $data = array(
            'addTime' => time(),
        );

        $this->db->update('sample', $data);

        return true;
    }
}
